<template>
  <div class="_wz_login">


<!--    background: rgba(0,0,0,0.2);-->
    <div class="_wz_login_right">
      <div style="width: 100%;height: 100%;position: relative;z-index: 2;display: flex;flex-direction: column;align-items: center;justify-content: center;">
        <img src="../../assets/logo.png" style="width: 80px;">
        <div style="font-size: 24px;font-weight: 900;line-height: 60px;">登录</div>
        <div style="font-size: 20px;color: #8290ac;line-height: 50px;letter-spacing: 2px;">欢迎登录交通运输综合监测平台</div>
        <div class="_wz_loginMethod">
          <div :class="{'_wz_loginAction_select' : loginAction == 1}" @click="loginAction = 1">账号登陆</div>
          <div :class="{'_wz_loginAction_select' : loginAction == 2}" @click="loginAction = 2">短信登陆</div>
        </div>

<!--        账号登陆-->

        <div style="min-height: 240px;display: flex;flex-direction: column;justify-content: space-between;width: 300px;">

          <template v-if="loginAction == 1">
            <Form ref="formDataSubmit" :model="formData" :rules="ruleInline" style="width: 100%;">
              <FormItem prop="username">
                <i-input prefix="ios-contact" type="text" size="large" v-model="formData.username" placeholder="请输入用户名" clearable @keyup.enter.native="handleSubmit"/>
              </FormItem>
              <FormItem prop="password">
                <i-input prefix="ios-lock-outline" password type="password" size="large" v-model="formData.password" placeholder="请输入密码" @keyup.enter.native="handleSubmit" />
              </FormItem>
              <FormItem>
                <Alert v-if="typeShow == 1" type="warning" show-icon>请插入身份认证U-Key</Alert>
                <Alert v-if="typeShow == 2" type="success" show-icon>身份认证已通过</Alert>
                <Alert v-if="typeShow == 3" type="error"  show-icon style="position: relative">
                  请下载安装身份认证U-Key驱动
                  <div style="position: absolute;right: 10px;top: 8px;cursor: pointer;color: #2d8cf0" @click="dowFile">下载</div>
                </Alert>
              </FormItem>
            </Form>
          </template>

  <!--        短信登陆-->
          <template v-if="loginAction == 2">
            <Form ref="formInlineSubmit" :model="formInline" :rules="ruleInlines" style="width: 100%;">
              <FormItem prop="mobile">
                <i-input prefix="ios-contact" type="text" size="large" v-model.number="formInline.mobile" placeholder="请输入手机号" clearable @keyup.enter.native="handleSubmit"/>
              </FormItem>
              <FormItem  style="margin-bottom: 68px" prop="safety_sms">
                <div style="position: relative;" >
                  <i-input  prefix="ios-lock-outline" type="text" size="large" v-model="formInline.safety_sms" placeholder="请输入验证码" @keyup.enter.native="handleSubmit"/>
                  <div style="position: absolute;top: 0;right: 10px;display: flex;align-items: center;height: 100%;cursor: pointer" @click="getAuthCode">
                    <div style="width: 2px;height: 24px;background: #d5d5d5;margin-right: 10px"></div>
                    <div style="width: 90px">{{ authName }}</div>
                  </div>
                </div>
              </FormItem>
            </Form>
          </template>

          <Button type="primary" @click="handleSubmit" long size="large">立即登录</Button>
        </div>

      </div>
    </div>




    <div class="_wz_foot">
        <span style="margin: 0px 5px;">
          <img src="../../assets/fbc3f9cd07cbbca6b965bfd7f7537c7.png">
          <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=13050902000113" style="color: rgb(147, 147, 147);">冀公网安备 13050902000113号</a>
        </span>
        <span style="margin: 0px 5px;">
          <a href="https://beian.miit.gov.cn/" target="_blank" style="color: rgb(147, 147, 147);"> 冀ICP备18004049号 </a>
        </span>
    </div>



    <!-- 修改密码 -->
    <Modal v-model="modifyPassword" title="修改密码" :mask-closable="false" :footer-hide="true" width="800" @on-visible-change="modifyPasswordFun">
      <changePassword v-if="modifyPassword" :loginSource="true"></changePassword>
    </Modal>
  </div>
</template>
<script>


import {getCurrentInstance,inject,nextTick,reactive, toRefs,toRef,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted, ref,defineComponent,toRaw,watch} from 'vue'
import { useRouter,useRoute } from "vue-router";
import { loadNav,getFirstMenu } from "../../router/dynamicRouting.js";
import { getMenu } from "../../util/getMenu.js";

import SoftKey3W from "../../util/Syunew3W"
import changePassword from "../userSetUp/changePassword.vue"



import {useMainStore} from '../../store'  //pinia 使用 类似 vuex
import {storeToRefs} from 'pinia'
//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex

//reactive
export default defineComponent({
  name: 'lgoin',//组件名称
  components: {
    changePassword,//修改密码
  },//组件引用
  setup () {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const $common = inject('$common');//自己封装的方法
    const router = useRouter();//路由跳转使用


    // 用于获取$refs
    const formDataSubmit = ref();
    const formInlineSubmit = ref();



    const state = reactive({
      typeShow:null,// uk 状态
      bConnect:0,// UK
      keyID:null,
      modifyPassword: false,//修改密码
      loginAction:1,//登陆方式


      authName:'获取验证码',
      countdown:60,
      //验证码
      formInline:{
        mobile:'',
        safety_sms:'',
        grant_type: 'password',
        scope: "read write",
        client_id: "xd-client-gov",
        client_secret: "xd-secret-gov",
        safety_type: 2
      },
      ruleInlines: {
        mobile: [{ type:'number',required: true, message: '请填写手机号', trigger: 'blur' }],
        safety_sms: [{ required: true, message: '请填写验证码', trigger: 'blur' }],
      },

      //密码
      formData:{
        username:'',//org_wangzhi
        password:'',//Ab@888888
        grant_type: 'password',
        scope: "read write",
        client_id: "xd-client-gov",
        client_secret: "xd-secret-gov",
        safety_type: 3
      },//表单数据
      ruleInline:{//正则
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        captcha: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ],
      },
    });



    //登录方法
    const handleSubmit = async()=>{

      if(state.loginAction == 1){
        formDataSubmit.value.validate(async(valid) => {
          if(valid){
            if (state.keyID){
              state.formData.safety_ukey = state.keyID
              console.log(state.keyID,'this.keyID')
            }else {
              delete state.formData.safety_ukey
            }

            $ViewUIPlus.Spin.show()//显示加载

            var data = state.formData;
            let formData = new FormData();
            for (let key in data) {
              formData.append(key, data[key]);
            }

            //登陆
            await $axios.post(apiUrl.cbsSignalPlatformLogin,formData).then(async(res) => {
              if (!!res) {
                // $ViewUIPlus.Spin.hide()//显示加载
                sessionStorage.setItem("loginData", JSON.stringify(res.data));
                getUserInfo();//获取用户数据
              }

            }).catch((err) => {
              console.log("失败", err)
            })


          }else{
            $ViewUIPlus.Message.error('请输入账号密码登录');
          }
        })
      }else{
        formInlineSubmit.value.validate(async(valid) => {
          if(valid){
            $ViewUIPlus.Spin.show()//显示加载
            var data = state.formData;
            let formData = new FormData();
            for (let key in data) {
              formData.append(key, data[key]);
            }
            //登陆
            await $axios.post(apiUrl.cbsSignalPlatformLogin,formData).then(async(res) => {
              if (!!res) {
                // $ViewUIPlus.Spin.hide()//显示加载
                sessionStorage.setItem("loginData", JSON.stringify(res.data));
                getUserInfo();//获取用户数据

              }
            }).catch((err) => {
              console.log("失败", err)
            })

          }else{
            $ViewUIPlus.Message.error('请输入手机号验证码登陆');
          }
        })
      }

    }

    //获取用户数据
    const getUserInfo = async()=>{

      //用户信息
      await $axios.post(apiUrl.systemLoginUserInfo).then(async(res) => {
        $ViewUIPlus.Spin.hide()//显示加载
        let loginData = JSON.parse(sessionStorage.getItem("loginData"));
        loginData.userInfo = res.data.data;
        sessionStorage.setItem("loginData", JSON.stringify(loginData));

        mainStore.userData = loginData;//用户数据


        if(passwordStrengthVerification(loginData.userInfo)){
          router.push({ path: await getMenu(true), query: {}})
        }


      }).catch((err) => {
        console.log("失败", err)
      })
    }

    //获取验证码
    const getAuthCode = ()=>{
      if (state.countdown == 60){
        if (!state.formInline.mobile){
          $ViewUIPlus.Message.error('请输入手机号')
          return false
        }
        $axios.post(apiUrl.oauthSmsSend,{mobile:state.formInline.mobile}).then((res) => {
          if (!!res) {
            authCode();
          }

        }).catch((err) => {
          console.log("失败", err)
        })
      }
    }

    //验证码初始化
    const authCode = () =>{
      if (state.countdown == 0) {
        state.authName="获取验证码";
        state.countdown = 60;
        return;
      } else {
        state.authName ="重新发送(" + state.countdown + ")";
        state.countdown--;
      }
      setTimeout(function() {authCode() } ,1000)
    }



    //密码强度校验
    const passwordStrengthVerification = (data)=>{
      let agentPassword = data.strength
      if (agentPassword == 0) {//弱密码
        $ViewUIPlus.Modal.confirm({
          title: '密码强度',
          content: '根据国家《网络安全法》要求，您的密码强度过低，请立刻修改！',
          onOk: () => {
            // that.personalCenter('changePassword');
            state.modifyPassword = true
          },
          onCancel: () => {//点击取消
            //退出
            sessionStorage.clear()// 删除所有数据
          }
        })
        return false;
      }
      return true;
    }

    //UK 下载
    const dowFile = ()=>{
      window.open('http://api.xdbj.net.cn:9446/media/ukey/SetUp.exe')
    }

    //
    const connectLoad = ()=>{
      try {
        var s_pnp = new SoftKey3W();
        s_pnp.Socket_UK.onopen = function() {
          state.bConnect = 1;//代表已经连接，用于判断是否安装了客户端服务
          setTimeout(() => login_onclick(), 500);
        }
        s_pnp.Socket_UK.onmessage =function got_packet(Msg) {
          var PnpData = JSON.parse(Msg.data);
          if(PnpData.type=="PnpEvent") { //如果是插拨事件处理消息
            if(PnpData.IsIn) {
              login_onclick()
              state.typeShow = 2 // 已插入
              // alert("UKEY已被插入，被插入的锁的路径是："+PnpData.DevicePath);
            } else {
              state.typeShow = 1 // 已拔出
              state.keyID = null
              // alert("UKEY已被拨出，被拨出的锁的路径是："+PnpData.DevicePath);
            }
          }
        }
        s_pnp.Socket_UK.onclose = function() {

        }

        setTimeout( () => {if(state.bConnect == 0) state.typeShow = 3}, 2000);//如果在一定时间内还没有连接成功，就提示要安装服务
      } catch(e) {
        $ViewUIPlus.Message.error(e.name + ": " + e.message,3);
        return false;
      }
    }

    const login_onclick = () =>{
      //判断是否安装了服务程序，如果没有安装提示用户安装
      if(state.bConnect == 0) {
        console.log("未能连接服务程序，请确定服务程序是否安装。");
        return false;
      }
      var DevicePath,ret,n,mylen,ID_1,ID_2;
      try {

        //由于是使用事件消息的方式与服务程序进行通讯，
        //好处是不用安装插件，不分系统及版本，控件也不会被拦截，同时安装服务程序后，可以立即使用，不用重启浏览器
        //不好的地方，就是但写代码会复杂一些
        var s_simnew1 = new SoftKey3W(); //创建UK类

        s_simnew1.Socket_UK.onopen = function() {
          s_simnew1.ResetOrder();//这里调用ResetOrder将计数清零，这样，消息处理处就会收到0序号的消息，通过计数及序号的方式，从而生产流程
        }

        //写代码时一定要注意，每调用我们的一个UKEY函数，就会生产一个计数，即增加一个序号，较好的逻辑是一个序号的消息处理中，只调用我们一个UKEY的函数
        s_simnew1.Socket_UK.onmessage = function got_packet(Msg) {
          var UK_Data = JSON.parse(Msg.data);
          // alert(Msg.data);
          if(UK_Data.type != "Process")return ;//如果不是流程处理消息，则跳过
          switch(UK_Data.order){
            case 0:{
              s_simnew1.FindPort(0);//发送命令取UK的路径
            }
              break;//!!!!!重要提示，如果在调试中，发现代码不对，一定要注意，是不是少了break,这个少了是很常见的错误
            case 1: {
              if( UK_Data.LastError != 0){
                console.log ( "未发现加密锁，请插入加密锁");
                state.typeShow = 1
                state.keyID = null
                // EventBus.$emit('alertKey', 2);
                s_simnew1.Socket_UK.close();
                return false;
              }
              state.typeShow = 2
              // EventBus.$emit('alertKey', 1);
              DevicePath = UK_Data.return_value;//获得返回的UK的路径
              s_simnew1.GetID_1(DevicePath); //发送命令取ID_1
            }
              break;
            case 2: {
              if( UK_Data.LastError != 0){ console.log("返回ID号错误，错误码为：" + UK_Data.LastError.toString());s_simnew1.Socket_UK.close();return false;}
              ID_1 = UK_Data.return_value;//获得返回的UK的ID_1
              s_simnew1.GetID_2(DevicePath); //发送命令取ID_2
            }
              break;
            case 3: {
              if( UK_Data.LastError != 0){ console.log("取得ID错误，错误码为：" + UK_Data.LastError.toString());s_simnew1.Socket_UK.close();return false;}
              ID_2=UK_Data.return_value;//获得返回的UK的ID_2

              state.keyID = toHex(ID_1) + toHex(ID_2);

              //所有工作处理完成后，关掉Socket
              s_simnew1.Socket_UK.close();
            }
              break;
          }
        }
        s_simnew1.Socket_UK.onclose = function(){

        }
        return true;
      }
      catch (e) {
        $ViewUIPlus.Message.error(e.name + ": " + e.message);
      }
    }

    const toHex = ( n ) => {
      var digitArray = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');

      var result = ''
      var start = true;

      for ( var i = 32; i > 0; ) {
        i -= 4;
        var digit = ( n >> i ) & 0xf;

        if (start && digit === 0){
          result += digitArray[digit];
        }

        if (!start || digit != 0) {
          start = false;
          result += digitArray[digit];
        }
      }

      return ( result == '' ? '0' : result );
    }


    //监听弹框
    const modifyPasswordFun =  (data)=> {
      if (!data) {
        sessionStorage.clear()// 删除所有数据
      }
    }



    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")

      connectLoad();//UK
    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")

      window.onresize = null;

    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      handleSubmit,//登录方法
      formDataSubmit,//ref 使用
      formInlineSubmit,//ref 使用
      getAuthCode,//获取验证按摩

      dowFile,//UK 下载
      modifyPasswordFun,//监听弹框
    }
  }
})


</script>
<style lang="less">
._wz_login {
  width: 100%;
  height: 100%;
  background-size: cover;
  position: relative;
  //background-image: url(../../assets/logi_back.png);
  background-image: url(../../assets/bg15.jpg);
  background-size: cover;
  background-position: 50%;
  position: relative;
  display: flex;
  justify-content: flex-end;



  ._wz_foot {
    z-index: 3;
    background: #fff;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 30px;
    line-height: 30px;
    text-align: center;
    box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
    overflow: hidden;
    color: rgba(0,0,0,.45);font-size: 14px;
    letter-spacing: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    span{
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  ._wz_login_right{
    height: 100%;width: 36%;min-width: 320px;
    position: relative;

  }
  ._wz_login_right::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.5);

    backdrop-filter: blur(10px);
  }
  ._wz_loginMethod{
    display: flex;margin-bottom: 30px;width: 170px;justify-content: space-around;
    line-height: 30px;
    div{
      font-size: 16px;
      color: #222;
      cursor: pointer;
      position: relative;
    }
    ._wz_loginAction_select{
      font-weight: 600;
    }
    ._wz_loginAction_select:before{
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 3px;
      background: rgb(3, 106, 187);
    }
  }

}
</style>
